package com.fsp.blog.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fsp.blog.dao.ArticleMapper;
import com.fsp.blog.pojo.Article;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author fushengping
 * @className ThreadService
 * @description
 * @date 2021/11/20 11:07
 */
@Component
public class ThreadService {
    //期望此线程在线程池执行，不会影响主线程
    /*将该方法丢入我们配置的线程池中*/
    @Async("taskExecutor")
    public void updateArticleVieCount(ArticleMapper articleMapper, Article article) {

        int viewCounts = article.getViewCounts(); //获取阅读前阅读数
        Article articleUpdate = new Article(); //接收阅读后的数据
        articleUpdate.setViewCounts(viewCounts + 1);
        /*拼接之后的sql语句为:
        * update article set view_count = 100 where id = 11 and view_count = 99  */
        LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Article::getId,article.getId()); //遍历id,进行判断是否等于查询文章id
        updateWrapper.eq(Article::getViewCounts,article.getViewCounts());
        articleMapper.update(articleUpdate,updateWrapper); //sql语句拼接完成,这样类似乐观锁

//        try {
//            Thread.sleep(5000);
//            System.out.println("更新完成了。。。");
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }
}
